//
//  LocationPointManager.m
//  ZBaiduDemo
//
//  Created by 周成龙 on 16/10/26.
//  Copyright © 2016年 ZCL. All rights reserved.
//

#import "LocationPoint.h"
#import "SQLiteTool.h"

@implementation LocationPoint

- (instancetype)initWithLatitude:(NSString *)latitude longitude:(NSString *)longitude {
    if (self = [super init]) {
        self.latitude = latitude;
        self.longitude = longitude;
        self.timeString = [self timeString];
    }
    return self;
}

- (void)insertPoint {
    if ([[SQLiteTool shareSQLiteTool] openDB]) {
        NSString *sql = [NSString stringWithFormat:@"INSERT INTO l_table (latitude, longitude, timeString) VALUES ('%@', '%@', '%@')", self.latitude, self.longitude, self.timeString];
        if ([[SQLiteTool shareSQLiteTool] execSql:sql]) {
            NSLog(@"数据插入成功");
        }
    }
    [[SQLiteTool shareSQLiteTool] closeDB];
}

+ (NSArray *)queryLocationPoint {
    if ([[SQLiteTool shareSQLiteTool] openDB]) {
        NSArray *dictArray = [[SQLiteTool shareSQLiteTool] qureySqlite:@"SELECT * FROM 'l_table';"];
        
        NSMutableArray *arr = [NSMutableArray array];
        for (int i = 0; i < dictArray.count; i ++) {
            LocationPoint *p = [[LocationPoint alloc] initModelWithDict:dictArray[i]];
            [arr addObject:p];
        }
        [[SQLiteTool shareSQLiteTool] closeDB];
        return arr;
    }else {
        [[SQLiteTool shareSQLiteTool] closeDB];
        return nil;
    }
}

- (instancetype)initModelWithDict:(NSDictionary *)dict
{
    if (self = [super init]) {
        [self setValuesForKeysWithDictionary:dict];
    }
    return self;
}

- (void)deleteAll {
    NSString *sql = @"drop table l_table;";
    if ([[SQLiteTool shareSQLiteTool] openDB]) {
        [[SQLiteTool shareSQLiteTool] qureySqlite:sql];
    }
    [[SQLiteTool shareSQLiteTool] closeDB];
}

- (void)deleteItem:(NSInteger)l_id {
    NSString *sql = [NSString stringWithFormat:@"delete from l_table where i_id=%ld;", l_id];
    if ([[SQLiteTool shareSQLiteTool] openDB]) {
        [[SQLiteTool shareSQLiteTool] qureySqlite:sql];
    }
    [[SQLiteTool shareSQLiteTool] closeDB];
}

- (NSString *)timeString {
    NSDate * date = [NSDate date];
    NSDateFormatter *outputFormat = [[NSDateFormatter alloc] init];
    [outputFormat setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString * newDateString = [outputFormat stringFromDate:date];
    return newDateString;
}

@end
